import ResultWrap from "@/components/ResultWrap";
import { addPost, getPost, updatePost } from "@/services/system/SystemController";
import { ModalForm, ProFormSwitch, ProFormText, ProFormTextArea } from "@ant-design/pro-components"
import { useRequest } from "@umijs/max";
import { Form } from "antd";
import { FC } from "react"

const PostForm: FC<{ id?: number, onClose: () => void, onFinsish: () => void }> = ({ id, onClose, onFinsish }) => {
    const [form] = Form.useForm<System.PostDo>();
    const { error: initError, run: init } = useRequest(() => id != undefined && id != 0 ? getPost(id) : Promise.resolve({}), {
        refreshDeps: [id],
        onSuccess: form.setFieldsValue
    })
    const { run: submit, loading: submiting } = useRequest((d) => id != undefined ? id == 0 ? addPost(d) : updatePost(id, d) : Promise.reject("null id"),
        {
            manual: true,
            throwOnError: true,
            onSuccess: () => {
                onClose()
                onFinsish()
            }
        })
    return <ModalForm<System.PostDo> open={Number.isInteger(id)}
        modalProps={{ onCancel: () => onClose(), destroyOnClose: true }} form={form} layout="horizontal"
        title={(id == 0 ? "新增" : "修改") + "岗位"}
        width={450}
        loading={submiting}
        onFinish={submit}
    >
        <ResultWrap error={id != undefined && id != 0 ? initError : undefined} reload={init}>
            <ProFormText label="岗位名称" name="name" rules={[{ min: 3, max: 32, required: true }]}></ProFormText>
            <ProFormText label="岗位编码" name="key" rules={[{ min: 3, max: 32, required: true }]}></ProFormText>
            <ProFormSwitch label="岗位状态" name="status" ></ProFormSwitch>
            <ProFormTextArea label="描述" name="description" rules={[{ max: 255 }]}></ProFormTextArea>
        </ResultWrap>
    </ModalForm>
}
export default PostForm